package com.CIM.CIM_Spring.controller;

import com.CIM.CIM_Spring.common.Result;
import com.CIM.CIM_Spring.dto.TifProcessInfoDto;
import com.CIM.CIM_Spring.service.TinTerrainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;


@RestController
@RequestMapping("/tinterrain")
public class TinTerrainController {
    @Autowired
    private TinTerrainService tinTerrainService;

    @Value("${cim.paths.tifs-input-path}")
    private String tifInputDir;

    @Value("${cim.paths.xyz-output-path}")
    private String outPutDir;

    @PostMapping("dem2tintiles")
    @CrossOrigin(value = {"http://localhost:3000", "http://localhost:5174"}, maxAge = 1800, allowedHeaders = "*")
    public Result<String> dem2tintiles(@RequestBody TifProcessInfoDto tifProcessInfoDto){
        tifProcessInfoDto.setInput(tifInputDir);
        tifProcessInfoDto.setOutput(outPutDir);
        String fileName = tinTerrainService.dem2tintiles(tifProcessInfoDto);
        fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
        return Result.success(fileName);
    }

    @GetMapping("/download/{fileName}")
    @CrossOrigin(value = {"http://localhost:3000", "http://localhost:5174"}, maxAge = 1800, allowedHeaders = "*")
    public void downLoad(HttpServletResponse response, @PathVariable("fileName") String name){
        // @TODO拿到fileName后构建File对象，将坐标txt文件使用request输出流传回浏览器
        try {
            String fileName = outPutDir + "//16//" + name;
            // 输入流，读取文件内容
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            // 输出流，将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            // 设置http响应头
            response.setContentType(getContentType(fileName));
            response.setHeader("Content-Disposition", "attachment; filename=\"" + name + "\"");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != - 1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getContentType(String fileName) throws IOException {
        // 获取文件扩展名
        String contentType = Files.probeContentType(new File(fileName).toPath());
        return contentType;
    }
}
